<template>
  <div class="sheep-change-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>羊场业务</el-breadcrumb-item>
      <el-breadcrumb-item>羊只淘汰</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="title">羊只淘汰</h1>
      <p class="subtitle">记录和管理羊只淘汰信息</p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" size="default" @click="addNewRecord" :icon="Plus" class="btn-primary">新增</el-button>
      <el-button type="success" size="default" @click="saveRecords" :icon="Check" class="btn-success">保存</el-button>
      <el-button size="default" @click="resetForm" :icon="RefreshRight" class="btn-reset">撤销</el-button>
      <el-button type="danger" size="default" @click="deleteSelected" :icon="Delete" class="btn-delete">删除</el-button>
      <!-- <el-button type="info" size="default" @click="testBackend" class="btn-test">测试后端</el-button> -->
    </div>

    <!-- 淘汰基本信息卡片 -->
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">淘汰基本信息</h3>
      </div>
      <div class="card-body">
        <el-form :model="eliminateInfo" label-width="120px" class="change-form">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="淘汰日期" class="form-item">
                <el-date-picker v-model="eliminateInfo.eliminationDate" type="datetime" placeholder="选择日期时间" 
                  format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.sssZ" class="form-input"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="羊只类型" class="form-item">
                <el-select v-model="eliminateInfo.sheepType" placeholder="请选择" class="form-input" clearable>
                  <el-option label="种公" value="种公" />
                  <el-option label="种母" value="种母" />
                  <el-option label="后裔" value="后裔" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据号" class="form-item">
                <el-input v-model="eliminateInfo.documentnumber" placeholder="请输入单据号" class="form-input" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 表格操作区域 -->
    <div class="table-section">
      <div class="section-header">
        <h3 class="section-title">淘汰明细</h3>
        <div class="table-actions">
          <el-button type="success" plain @click="addRow" :icon="Plus" class="btn-table-action">增行</el-button>
          <el-button type="danger" plain @click="deleteRow" :icon="Delete" class="btn-table-action">删行</el-button>
        </div>
      </div>

      <!-- 编辑表格 -->
      <el-table :data="editingData" border style="width: 100%" class="edit-table"
        :row-style="{ transition: 'all 0.3s' }" v-loading="false">
        <el-table-column prop="index" label="序号" width="60" align="center" />
        <el-table-column prop="earNumber" label="耳号" width="120">
          <template #default="{ row }">
            <el-input v-model="row.earNumber" placeholder="请输入耳号" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="variety" label="品种" width="120">
          <template #default="{ row }">
            <el-input v-model="row.variety" placeholder="请输入品种" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="building" label="当前栋舍" width="120">
          <template #default="{ row }">
            <el-select v-model="row.building" placeholder="请选择" class="table-input">
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="column" label="当前栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.column" placeholder="请输入栏位" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="exitStatus" label="离场状态" width="120">
          <template #default="{ row }">
            <el-input v-model="row.exitStatus" placeholder="请输入离场状态" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="eliminates" label="淘汰原因" width="180">
          <template #default="{ row }">
            <el-input v-model="row.eliminates" placeholder="请输入淘汰原因" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="handle" label="处理措施">
          <template #default="{ row }">
            <el-input v-model="row.handle" placeholder="请输入处理措施" class="table-input" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 操作提示 -->
      <div class="hint" v-if="editingData.length === 0">
        <el-alert title="提示信息" description="点击'增行'按钮添加淘汰明细数据" type="info" :closable="false" class="info-alert" />
      </div>
    </div>

    <!-- 已保存记录 -->
    <div class="saved-records-section" v-if="savedData.length > 0">
      <h3 class="section-title">已保存记录</h3>
      <el-table :data="savedData" border style="width: 100%" class="saved-table" :row-style="{ transition: 'all 0.3s' }"
        highlight-current-row @row-click="handleRowClick">
        <el-table-column prop="index" label="序号" width="60" align="center" />
        <el-table-column prop="earNumber" label="耳号" width="120" />
        <el-table-column prop="variety" label="品种" width="120" />
        <el-table-column prop="building" label="当前栋舍" width="120" />
        <el-table-column prop="column" label="当前栏位" width="120" />
        <el-table-column prop="exitStatus" label="退出状态" width="120" />
        <el-table-column prop="eliminates" label="淘汰原因" width="180" />
        <el-table-column prop="handle" label="处理措施" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="editRecord(row)" :icon="Edit" class="edit-link">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Check, RefreshRight, Delete, Edit } from '@element-plus/icons-vue'
import axios from 'axios'

// 定义表格行数据类型 - 根据后端API调整
interface EliminateRecord {
  eliminateId: number
  earNumber: string
  variety: string
  building: string
  column: string
  exitStatus: string
  eliminates: string
  handle: string
  isDeleted: boolean
}

// 表单数据类型 - 根据后端API调整
interface EliminateInfo {
  eliminationDate: string
  sheepType: string
  documentnumber: string
}

// 表单数据 - 使用reactive确保响应式
const eliminateInfo = reactive<EliminateInfo>({
  eliminationDate: '',
  sheepType: '',
  documentnumber: ''
})

// 表格数据
const editingData = ref<EliminateRecord[]>([])
const savedData = ref<EliminateRecord[]>([])
let recordIndex = 1

const addNewRecord = () => {
  editingData.value = []
  addRow()
}

const addRow = () => {
  editingData.value.push({
    eliminateId: 0,
    earNumber: '',
    variety: '',
    building: '',
    column: '',
    exitStatus: '',
    eliminates: '',
    handle: '',
    isDeleted: false
  })
}

const deleteRow = () => {
  if (editingData.value.length > 0) {
    editingData.value.pop()
    if (editingData.value.length === 0) {
      recordIndex = 1
    }
  }
}

// 保存数据到后端 - 参考Death页面的实现
const saveRecords = async () => {
  try {
    // 验证表单数据
    if (!eliminateInfo.eliminationDate) {
      ElMessage.warning('请选择淘汰日期')
      return
    }
    if (!eliminateInfo.sheepType) {
      ElMessage.warning('请选择羊只类型')
      return
    }
    if (!eliminateInfo.documentnumber) {
      ElMessage.warning('请输入单据号')
      return
    }

    // 校验表格数据
    if (!editingData.value || editingData.value.length === 0) {
      ElMessage.warning('请至少添加一条淘汰记录')
      return
    }

    // 过滤有效数据（至少有一个字段不为空）
    const validRecords = editingData.value.filter(row => 
      row.earNumber || row.variety || row.building || row.column || row.exitStatus || row.eliminates || row.handle
    )

    if (validRecords.length === 0) {
      ElMessage.warning('请至少填写一条完整的淘汰记录')
      return
    }

    // 构建API请求数据 - 根据后端API要求
    const apiPayload = {
      eliminationDate: eliminateInfo.eliminationDate, // 已经是ISO格式
      sheepType: eliminateInfo.sheepType,
      documentnumber: eliminateInfo.documentnumber,
      eliminatesList: validRecords.map(row => ({
        eliminateId: row.eliminateId,
        earNumber: row.earNumber,
        variety: row.variety,
        building: row.building,
        column: row.column,
        exitStatus: row.exitStatus,
        eliminates: row.eliminates,
        handle: row.handle,
        isDeleted: row.isDeleted
      }))
    }

    console.log('发送到后端的数据:', JSON.stringify(apiPayload, null, 2))

    // 使用axios发送请求到CreateEliminate接口
    console.log('开始发送请求到:', 'http://localhost:5008/api/Management/CreateEliminate')
    console.log('请求数据:', apiPayload)
    
    const response = await axios.post('http://localhost:5008/api/Management/CreateEliminate', apiPayload, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('后端响应状态:', response.status)
    console.log('后端响应数据:', response.data)
    console.log('完整响应:', response)

    if (response.status === 200) {
      // 检查响应数据中的成功标识
      if (response.data && (response.data.success === true || response.data.code === 200 || response.data.message === 'success' || response.data.code === 100)) {
        ElMessage.success(`保存成功，共保存${validRecords.length}条记录`)
        
        // 清空表单数据
        eliminateInfo.eliminationDate = ''
        eliminateInfo.sheepType = ''
        eliminateInfo.documentnumber = ''
        
        // 重置表格数据
        editingData.value = []
        recordIndex = 1
      } else {
        console.log('后端返回失败状态:', response.data)
        ElMessage.error(`保存失败: ${response.data?.message || response.data?.msg || '后端返回失败状态'}`)
      }
    } else {
      console.log('HTTP状态码不是200:', response.status)
      ElMessage.error(`保存失败，HTTP状态码: ${response.status}`)
    }
  } catch (error: any) {
    console.log('=== 请求异常详情 ===')
    console.error('保存失败:', error)
    console.log('错误类型:', typeof error)
    console.log('错误对象:', error)
    
    if (error.response) {
      // 服务器响应了错误状态码
      console.log('错误响应状态:', error.response.status)
      console.log('错误响应数据:', error.response.data)
      console.log('错误响应头:', error.response.headers)
      
      // 特别处理400错误，显示详细验证信息
      if (error.response.status === 400) {
        console.log('=== 400错误详细信息 ===')
        console.log('错误类型:', error.response.data?.type)
        console.log('错误标题:', error.response.data?.title)
        console.log('错误状态:', error.response.data?.status)
        console.log('验证错误:', error.response.data?.errors)
        console.log('追踪ID:', error.response.data?.traceId)
      }
      
      if (error.response.status === 404) {
        ElMessage.error('保存失败: API接口不存在(404)，请检查后端路由配置')
      } else if (error.response.status === 401) {
        ElMessage.error('保存失败: 未授权(401)，请检查认证信息')
      } else if (error.response.status === 400) {
        console.log('400错误详情:', error.response.data)
        if (error.response.data?.errors) {
          // 显示具体的验证错误
          const validationErrors = error.response.data.errors
          let errorMessage = '保存失败: 数据验证错误\n'
          for (const field in validationErrors) {
            errorMessage += `${field}: ${validationErrors[field].join(', ')}\n`
          }
          ElMessage.error(errorMessage)
        } else {
          ElMessage.error(`保存失败: 请求参数错误(400) - ${error.response.data?.title || error.response.data?.message || '请检查数据格式'}`)
        }
      } else if (error.response.status === 500) {
        ElMessage.error('保存失败: 服务器内部错误(500)')
      } else {
        ElMessage.error(`保存失败: ${error.response.status} - ${error.response.data?.message || error.response.data?.msg || '服务器错误'}`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.log('网络请求失败:', error.request)
      ElMessage.error('保存失败: 网络连接异常，请检查后端服务是否启动在端口5008')
    } else if (error.code === 'ECONNABORTED') {
      // 请求超时
      console.log('请求超时:', error.message)
      ElMessage.error('保存失败: 请求超时，请检查网络连接')
    } else {
      // 其他错误
      console.log('其他错误:', error.message)
      ElMessage.error(`保存失败: ${error.message}`)
    }
  }
}

const editRecord = (record: EliminateRecord) => {
  editingData.value = [JSON.parse(JSON.stringify(record))]
}

const resetForm = () => {
  editingData.value = []
  recordIndex = 1
  // 清空表单数据
  eliminateInfo.eliminationDate = ''
  eliminateInfo.sheepType = ''
  eliminateInfo.documentnumber = ''
}

const deleteSelected = () => {
  if (savedData.value.length > 0) {
    ElMessageBox.confirm('确定要删除所有已保存的记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      savedData.value = []
      ElMessage.success('删除成功')
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  } else {
    ElMessage.warning('没有可删除的记录')
  }
}

const handleRowClick = (row: EliminateRecord) => {
  console.log('点击了行:', row)
}

// 测试后端连接 - 参考Death页面的实现
const testBackend = async () => {
  try {
    console.log('=== 测试后端连接 ===')
    
    // 测试不同的端点
    const testUrls = [
      'http://localhost:5008/api',
      'http://localhost:5008/api/Management',
      'http://localhost:5008/api/Management/CreateEliminate',
      'http://localhost:5008/api/Test'
    ]
    
    for (const url of testUrls) {
      try {
        console.log(`测试URL: ${url}`)
        const response = await axios.get(url, {
          timeout: 5000,
          headers: {
            'Accept': 'application/json'
          }
        })
        console.log(`URL ${url} 测试成功:`, response.status, response.data)
        ElMessage.success(`后端连接成功 - ${url}`)
        return
      } catch (urlError: any) {
        console.log(`URL ${url} 测试失败:`, urlError.response?.status || urlError.message)
      }
    }
    
    // 如果所有GET请求都失败，尝试POST请求
    console.log('尝试POST请求测试...')
    const testData = {
      eliminationDate: "2025-01-01T00:00:00.000Z",
      sheepType: "test",
      documentnumber: "test",
      eliminatesList: [{
        eliminateId: 0,
        earNumber: "test",
        variety: "test",
        building: "test",
        column: "test",
        exitStatus: "test",
        eliminates: "test",
        handle: "test",
        isDeleted: false
      }]
    }
    
    const postResponse = await axios.post('http://localhost:5008/api/Management/CreateEliminate', testData, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('POST测试成功:', postResponse.status, postResponse.data)
    ElMessage.success('后端POST接口测试成功')
    
  } catch (error: any) {
    console.log('=== 后端测试失败 ===')
    console.error('测试失败:', error)
    
    if (error.response) {
      console.log('错误响应状态:', error.response.status)
      console.log('错误响应数据:', error.response.data)
      ElMessage.error(`后端测试失败: ${error.response.status} - ${error.response.data?.message || '服务器错误'}`)
    } else if (error.request) {
      console.log('网络请求失败:', error.request)
      ElMessage.error('后端测试失败: 无法连接到服务器，请检查后端服务是否启动')
    } else {
      console.log('其他错误:', error.message)
      ElMessage.error(`后端测试失败: ${error.message}`)
    }
  }
}
</script>

<style scoped>
/* 全局容器样式 */
.sheep-change-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 20px;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 28px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f56c6c;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

/* 操作按钮样式 */
.action-buttons {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn-primary,
.btn-success,
.btn-reset,
.btn-delete,
.btn-test {
  transition: all 0.3s ease;
}

/* 新增按钮 - 深红色渐变 */
.btn-primary {
  background: linear-gradient(135deg, #c62828 0%, #a31515 100%) !important;
  border-color: #c62828 !important;
  color: white !important;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #b71c1c 0%, #8e0000 100%) !important;
  border-color: #b71c1c !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(198, 40, 40, 0.4);
}

/* 保存按钮 - 深红色渐变 */
.btn-success {
  background: linear-gradient(135deg, #c62828 0%, #a31515 100%) !important;
  border-color: #c62828 !important;
  color: white !important;
}

.btn-success:hover {
  background: linear-gradient(135deg, #b71c1c 0%, #8e0000 100%) !important;
  border-color: #b71c1c !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(198, 40, 40, 0.4);
}

/* 撤销按钮 - 深红色渐变 */
.btn-reset {
  background: linear-gradient(135deg, #c62828 0%, #a31515 100%) !important;
  border-color: #c62828 !important;
  color: white !important;
}

.btn-reset:hover {
  background: linear-gradient(135deg, #b71c1c 0%, #8e0000 100%) !important;
  border-color: #b71c1c !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(198, 40, 40, 0.4);
}

/* 删除按钮 - 深红色渐变 */
.btn-delete {
  background: linear-gradient(135deg, #c62828 0%, #a31515 100%) !important;
  border-color: #c62828 !important;
  color: white !important;
}

.btn-delete:hover {
  background: linear-gradient(135deg, #b71c1c 0%, #8e0000 100%) !important;
  border-color: #b71c1c !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(198, 40, 40, 0.4);
}

/* 测试按钮 - 深红色渐变 */
.btn-test {
  background: linear-gradient(135deg, #c62828 0%, #a31515 100%) !important;
  border-color: #c62828 !important;
  color: white !important;
}

.btn-test:hover {
  background: linear-gradient(135deg, #b71c1c 0%, #8e0000 100%) !important;
  border-color: #b71c1c !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(198, 40, 40, 0.4);
}

/* 卡片样式 */
.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.card-body {
  padding: 24px;
}

/* 表单样式 */
.change-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  transition: all 0.3s ease;
}

.form-input:hover {
  border-color: #c0c4cc;
}

.form-input:focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
}

/* 表格区域样式 */
.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  padding: 24px;
  transition: all 0.3s ease;
}

.table-section:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.btn-table-action {
  transition: all 0.3s ease;
  border-width: 1px;
}

.btn-table-action:hover {
  transform: translateY(-1px);
}

/* 表格样式 */
.edit-table,
.saved-table {
  border-radius: 4px;
  overflow: hidden;
}

.edit-table .el-table__header-wrapper th,
.saved-table .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #303133;
}

.edit-table .el-table__body-wrapper tr:hover,
.saved-table .el-table__body-wrapper tr:hover {
  background-color: #fafafa;
}

.table-input {
  transition: all 0.3s ease;
}

.table-input:hover {
  border-color: #c0c4cc;
}

.table-input:focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
}

/* 提示信息样式 */
.hint {
  margin-top: 16px;
}

.info-alert {
  border-radius: 4px;
}

/* 已保存记录区域样式 */
.saved-records-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
  transition: all 0.3s ease;
}

.saved-records-section:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.edit-link {
  color: #f56c6c;
  transition: all 0.3s ease;
}

.edit-link:hover {
  color: #f78989;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .sheep-change-container {
    padding: 16px;
  }

  .action-buttons {
    justify-content: center;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-body,
  .table-section,
  .saved-records-section {
    padding: 16px;
  }
}
</style>